package com.heima.test1;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class Test {
    public static void main(String[] args) throws IOException {
        statistics("窗里窗外.txt", "GBK");
    }

    public static void statistics(String fileString, String charset) throws IOException {
        File file = new File(fileString);
        //判空
        if (!file.exists()) {
            System.out.println("读取文件不存在!");
            return;
        }
        FileReader fr = new FileReader(file, Charset.forName(charset));
        // 怎么放在同一文件下
        String nFile = fileString.substring(0, fileString.indexOf(file.getName()));// 相对路径
        FileWriter fw = new FileWriter(nFile + "count.properties", Charset.forName("UTF-8"));
        int len;
        Properties ppt = new Properties();// 存放容器
        while ((len = fr.read()) != -1) {
            char c = (char) len;
            // properties里只能存放字符串
            String s = String.valueOf(c);
            // 判断ppt里是否包含某个key(读取的某个字是否已经存在)
            if (!ppt.containsKey(s)) {
                ppt.setProperty(s, "1");//不包含,就是第一次
            } else {
                // 包含,获取对应的value,properties中key和value都是字符串,将字符串数字取为整型,再+1,存入ppt
                String v = ppt.getProperty(s);
                int i = Integer.parseInt(v) + 1;//提示这里的v是null?
                ppt.setProperty(s, String.valueOf(i));
            }
        }
        // 处理getName是GBK,需要的是UTF-8的问题
        byte[] bytes = fileString.getBytes();
        String oldName = new String(bytes, Charset.forName("GBK"));
        String newName = new String(oldName.getBytes(), StandardCharsets.UTF_8);
        ppt.store(fw, "统计<" + newName + ">字数:");
        // 释放
        fr.close();
        fw.close();
    }
}